# SqlsugarService.API 启动诊断脚本
# 用于诊断应用程序启动失败的问题

param(
    [string]$PublishPath = "bin\Release\net6.0\publish",
    [switch]$Verbose = $false
)

Write-Host "=== SqlsugarService.API 启动诊断 ===" -ForegroundColor Green

# 1. 检查发布文件
Write-Host "`n1. 检查发布文件..." -ForegroundColor Yellow
$requiredFiles = @(
    "SqlsugarService.API.dll",
    "SqlsugarService.API.exe", 
    "appsettings.json",
    "web.config"
)

$missingFiles = @()
foreach ($file in $requiredFiles) {
    $filePath = Join-Path $PublishPath $file
    if (Test-Path $filePath) {
        Write-Host "✅ $file 存在" -ForegroundColor Green
    } else {
        Write-Host "❌ $file 缺失" -ForegroundColor Red
        $missingFiles += $file
    }
}

if ($missingFiles.Count -gt 0) {
    Write-Host "缺失关键文件，请重新发布项目" -ForegroundColor Red
    exit 1
}

# 2. 检查.NET运行时
Write-Host "`n2. 检查.NET运行时..." -ForegroundColor Yellow
try {
    $dotnetVersion = dotnet --version
    Write-Host "✅ .NET 版本: $dotnetVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ .NET 运行时未安装或不可用" -ForegroundColor Red
    Write-Host "请安装 .NET 6.0 运行时" -ForegroundColor Yellow
    exit 1
}

# 3. 检查配置文件
Write-Host "`n3. 检查配置文件..." -ForegroundColor Yellow
$configPath = Join-Path $PublishPath "appsettings.json"
try {
    $config = Get-Content $configPath | ConvertFrom-Json
    
    # 检查数据库连接字符串
    if ($config.ConnectionStrings.DefaultConnection) {
        Write-Host "✅ 数据库连接字符串已配置" -ForegroundColor Green
        if ($Verbose) {
            Write-Host "   连接字符串: $($config.ConnectionStrings.DefaultConnection)" -ForegroundColor Gray
        }
    } else {
        Write-Host "⚠️  数据库连接字符串未配置" -ForegroundColor Yellow
    }
    
    # 检查日志配置
    if ($config.Logging) {
        Write-Host "✅ 日志配置已设置" -ForegroundColor Green
    }
    
} catch {
    Write-Host "❌ 配置文件格式错误: $($_.Exception.Message)" -ForegroundColor Red
}

# 4. 测试直接启动
Write-Host "`n4. 测试应用程序启动..." -ForegroundColor Yellow
$dllPath = Join-Path $PublishPath "SqlsugarService.API.dll"

Write-Host "尝试启动应用程序..." -ForegroundColor Cyan

# 简单的启动测试
try {
    Set-Location $PublishPath
    Write-Host "当前目录: $(Get-Location)" -ForegroundColor Gray

    # 检查是否可以直接运行
    Write-Host "测试应用程序是否可以启动..." -ForegroundColor Cyan

    # 设置环境变量
    $env:ASPNETCORE_ENVIRONMENT = 'Development'
    $env:ASPNETCORE_URLS = 'http://localhost:5000'

    # 尝试启动应用（短时间测试）
    $processInfo = New-Object System.Diagnostics.ProcessStartInfo
    $processInfo.FileName = "dotnet"
    $processInfo.Arguments = "SqlsugarService.API.dll"
    $processInfo.UseShellExecute = $false
    $processInfo.RedirectStandardOutput = $true
    $processInfo.RedirectStandardError = $true
    $processInfo.CreateNoWindow = $true

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $processInfo

    Write-Host "启动进程..." -ForegroundColor Gray
    $started = $process.Start()

    if ($started) {
        # 等待一小段时间看是否立即退出
        Start-Sleep -Seconds 2

        if (!$process.HasExited) {
            Write-Host "✅ 应用程序启动成功" -ForegroundColor Green

            # 尝试读取输出
            $output = $process.StandardOutput.ReadToEnd()
            $error = $process.StandardError.ReadToEnd()

            if ($output) {
                Write-Host "标准输出:" -ForegroundColor Gray
                Write-Host $output -ForegroundColor Gray
            }

            # 停止进程
            $process.Kill()
            Write-Host "测试进程已停止" -ForegroundColor Gray

        } else {
            Write-Host "❌ 应用程序立即退出" -ForegroundColor Red

            # 读取错误输出
            $error = $process.StandardError.ReadToEnd()
            if ($error) {
                Write-Host "错误输出:" -ForegroundColor Red
                Write-Host $error -ForegroundColor Red
            }
        }
    } else {
        Write-Host "❌ 无法启动进程" -ForegroundColor Red
    }

} catch {
    Write-Host "❌ 启动测试失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 5. 检查端口占用
Write-Host "`n5. 检查端口占用..." -ForegroundColor Yellow
try {
    $portCheck = netstat -an | Select-String ":5000"
    if ($portCheck) {
        Write-Host "⚠️  端口5000可能被占用:" -ForegroundColor Yellow
        Write-Host $portCheck -ForegroundColor Gray
    } else {
        Write-Host "✅ 端口5000可用" -ForegroundColor Green
    }
} catch {
    Write-Host "无法检查端口状态" -ForegroundColor Yellow
}

# 6. 提供解决建议
Write-Host "`n=== 解决建议 ===" -ForegroundColor Magenta

if ($missingFiles.Count -gt 0) {
    Write-Host "• 重新发布项目: dotnet publish --configuration Release" -ForegroundColor White
}

Write-Host "• 检查数据库连接是否正常" -ForegroundColor White
Write-Host "• 确保防火墙允许端口5000" -ForegroundColor White
Write-Host "• 查看Windows事件日志中的应用程序错误" -ForegroundColor White
Write-Host "• 尝试在命令行中直接运行: dotnet SqlsugarService.API.dll" -ForegroundColor White
Write-Host "• 启用详细日志: 设置环境变量 ASPNETCORE_ENVIRONMENT=Development" -ForegroundColor White

Write-Host "`n=== 手动测试命令 ===" -ForegroundColor Magenta
Write-Host "cd $PublishPath" -ForegroundColor Cyan
Write-Host "`$env:ASPNETCORE_ENVIRONMENT='Development'" -ForegroundColor Cyan
Write-Host "`$env:ASPNETCORE_URLS='http://localhost:5000'" -ForegroundColor Cyan
Write-Host "dotnet SqlsugarService.API.dll" -ForegroundColor Cyan

Write-Host "`n诊断完成!" -ForegroundColor Green
